package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(version = "1.0.0") //申明这是一个dubbo服务
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询以为得分最高的推荐用户,在MongoDB中查询
     *
     * @param userId
     * @return
     */
    @Override
    public RecommendUser findWithMaxScore(Long userId) {//此处的userId应该是登录用户的id
        //查询得分最高的用户，按照得分倒序排序
        //因为一个登录用户的ID对应的有缘人不止一位,所以先根据toUserId查询到所有有缘人之后根据得分做一个倒序排序,
        //再选择第一位就是我们需要获取的今日佳人
        Query query = Query.query(Criteria.where("toUserId").is(userId))
                .with(Sort.by(Sort.Order.desc("score")))
                .limit(1);//
        RecommendUser one = mongoTemplate.findOne(query, RecommendUser.class);
        return one;
    }

    /**
     * 查询有缘人列表的方法,按照得分倒序
     *
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<RecommendUser> findPageInfo(Long userId, Integer pageNum, Integer pageSize) {
        //分页并且根据得分倒序排序
        PageRequest pageRequest = new PageRequest(pageNum - 1, pageSize, Sort.by(Sort.Order.desc("score")));
        //分页参数使用根据toUserId查询有缘人
        Query query = Query.query(Criteria.where("toUserId").is(userId)).with(pageRequest);
        List<RecommendUser> recommendUsers = mongoTemplate.find(query, RecommendUser.class);
        return new PageInfo<>(0, pageNum, pageSize, recommendUsers);
    }

    /**
     * 查看缘分值
     *
     * @param userId
     * @param toUserId
     * @return
     */
    @Override
    public Double findScore(Long userId, Long toUserId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("toUserId").is(toUserId));
        RecommendUser user = mongoTemplate.findOne(query, RecommendUser.class);
        if (null != user) {
            return user.getScore();
        }
        return null;
    }

}
